﻿using System;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.WindowsAzure;
using System.Collections.Generic;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace McCloudCore
{
    class McBlob
    {
        private string _Percent = "";
        public string getPercent() { return _Percent; }

        public void create(string key, string index, string results)
        {
            StorageAccountInfo accountBlob = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration();
            BlobStorage blobStorage = BlobStorage.Create(accountBlob);
            blobStorage.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
            blobStorage = BlobStorage.Create(accountBlob);            
            BlobContainer container = blobStorage.GetBlobContainer("mcc" + key);
            if (!container.DoesContainerExist()) container.CreateContainer();

            using (Stream stream = new MemoryStream())
            {
                byte[] bytes = Encoding.Default.GetBytes(results);
                stream.Write(bytes,0,bytes.Length);                
                stream.Flush();
                BlobContents contents = new BlobContents(stream);
                BlobProperties properties = new BlobProperties(key + index + ".dat");                
                stream.Seek(0, SeekOrigin.Begin);
                container.CreateBlob(properties, contents, true);
                stream.Close();
                
            }
        }


        public double count(string key)
        {
            string containerName = "mcc" + key;
            StorageAccountInfo accountBlob = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration();
            BlobStorage blobStorage = BlobStorage.Create(accountBlob);
            blobStorage.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
            blobStorage = BlobStorage.Create(accountBlob);
            BlobContainer container = blobStorage.GetBlobContainer(containerName);            
            if (!container.DoesContainerExist()) container.CreateContainer();
            return container.ListBlobs(key, false).Count();
        }
        
        
        public string concatenate(string key, double tasks)
        {   
            string containerName = "mcc" + key;
            StorageAccountInfo accountBlob = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration();
            BlobStorage blobStorage = BlobStorage.Create(accountBlob);
            blobStorage.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
            blobStorage = BlobStorage.Create(accountBlob);
            BlobContainer container = blobStorage.GetBlobContainer(containerName);
            if (!container.DoesContainerExist()) container.CreateContainer();
            
            string filesRoot = RoleEnvironment.GetLocalResource("McCloudStorage").RootPath;
            string file = Path.Combine(filesRoot, key + ".temp");
            FileStream fileStream = new FileStream(file, FileMode.Create);
            
            for (double i = 0; i < tasks; i++)
            {                
                string blobName = key + (i + 1).ToString() + ".dat";
                if(i % 100 == 0) Log.WriteInformation("Concatenando - está no " + (i+1).ToString() + " - " + blobName);
                MemoryStream memoryStream = new MemoryStream();
                BlobContents contents = new BlobContents(memoryStream);
                container.GetBlob(blobName, contents, false);
                memoryStream.Seek(0, SeekOrigin.Begin);
                StreamReader reader = new StreamReader(memoryStream);
                byte[] bytes = Encoding.Default.GetBytes(reader.ReadToEnd());                
                fileStream.Write(bytes, 0, bytes.Length);
                memoryStream.Close();
            }            
            fileStream.Close();

            return file;
        }

        public string getUri(string key, string index)
        {
            try
            {
                string containerName = "mcc" + key;
                StorageAccountInfo accountBlob = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration();
                BlobStorage blobStorage = BlobStorage.Create(accountBlob);
                blobStorage.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
                blobStorage = BlobStorage.Create(accountBlob);
                BlobContainer container = blobStorage.GetBlobContainer(containerName);
                container.SetContainerAccessControl(ContainerAccessControl.Public);
                if (!container.DoesContainerExist()) container.CreateContainer();
                string blobName = key + index + ".dat";
                if (container.DoesBlobExist(blobName)) return container.ContainerUri + "/" + blobName;   
                else return "N/A";
            }
            catch (Exception exception)
            {
                return "ERROR: " + exception.ToString();
            }
        }

        public void onStartContainer()
        {
            try
            {
                StorageAccountInfo accountBlob = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration();
                BlobStorage blobStorage = BlobStorage.Create(accountBlob);
                blobStorage.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
                blobStorage = BlobStorage.Create(accountBlob);
                BlobContainer container = blobStorage.GetBlobContainer("onstart");
                container.SetContainerAccessControl(ContainerAccessControl.Public);
                if (!container.DoesContainerExist()) return;
                McHotspoot.McHotspotI hotspoot =  McHotspoot.McHotspotFactory.create();
               
                string filesRoot = RoleEnvironment.GetLocalResource("McCloudStorage").RootPath;
                foreach (BlobProperties  blobItem in container.ListBlobs("",false))
                {
                    string blobName = blobItem.Name;
                    string file = Path.Combine(filesRoot, blobName);                                        
                    MemoryStream memoryStream = new MemoryStream();
                    BlobContents contents = new BlobContents(memoryStream);
                    if (!container.DoesBlobExist(blobName)) continue;
                    container.GetBlob(blobName, contents, false);                                        
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    FileStream fileStream1 = new FileStream(file, FileMode.Create);
                    byte[] bytes = memoryStream.ToArray();
                    fileStream1.Write(bytes, 0, bytes.Length);
                    fileStream1.Close();
                    memoryStream.Close();
                }
            }
            catch { return; }
        }

        public bool exist(string key, double index)
        {            
            try
            {
                string containerName = "mcc" + key;
                StorageAccountInfo accountBlob = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration();
                BlobStorage blobStorage = BlobStorage.Create(accountBlob);
                blobStorage.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(5, TimeSpan.FromSeconds(5));
                blobStorage = BlobStorage.Create(accountBlob);
                BlobContainer container = blobStorage.GetBlobContainer(containerName);
                container.SetContainerAccessControl(ContainerAccessControl.Public);
                if (!container.DoesContainerExist()) container.CreateContainer();
                string blobName = key + index.ToString() + ".dat";
                if (container.DoesBlobExist(blobName)) return true;
                else return false;
            }
            catch (Exception exception)
            {
                return false;
            }

        }
        
    }
}
